//
//  WDInputVinPlateNumberView.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/8/23.
//

#import "WDInputVinPlateNumberView.h"
#import "WDInputVinPlateNumberViewModel.h"
#import "RZCarPlateNoTextField.h"
#import "RZCarPlateNoKeyBoardViewModel.h"

@interface WDInputVinPlateNumberView ()
@property (nonatomic, strong) WDInputVinPlateNumberViewModel *viewModel;

/// 号码数量
@property (nonatomic, assign) NSUInteger plateLength;

@property (nonatomic, strong) UIView *textFieldContentView;

@property (nonatomic, strong) NSMutableArray <RZCarPlateNoTextField *> *textFields;

@property (nonatomic, strong) NSMutableArray <NSString *> *plateInputs;

@property (nonatomic, copy) NSString *plateNo;

@property (nonatomic, strong) UILabel *tipLabel;


@end

@implementation WDInputVinPlateNumberView

- (instancetype)initWithFrame:(CGRect)frame plateLength:(NSUInteger)plateLength {
    self.plateLength = plateLength;
    return [self initWithFrame:frame];
}

- (void)initWithVar {
    [super initWithVar];
    _textFields = [NSMutableArray new];
    _plateInputs = [NSMutableArray new];
    if (self.plateLength == 0) {
        self.plateLength = 8;
    }
}

- (void)initWithSubView {
    [super initWithSubView];
    
//    self.backgroundColor = [UIColor orangeColor];
    
    [self initWithTextFieldContentView];
    
    [self initWithTextFields];
    
    [self initTextFields];
    
    [self initWithTipLabel];
}


- (void)initWithTextFieldContentView {
    if (!_textFieldContentView) {
        CGRect frame = CGRectMake(0, 0, self.width, 60);
        _textFieldContentView = [[UIView alloc] initWithFrame:frame];
        _textFieldContentView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_textFieldContentView];
    }
}

- (void)initWithTipLabel {
    if (!_tipLabel) {
        CGRect frame = CGRectMake(18, self.height - 18, self.width - 18 * 2, 18);
        _tipLabel = [UILabel createWithLabel:self frame:frame font:[UIFont systemFontOfSize:12 weight:UIFontWeightRegular] propertiesBlock:^(UILabel * _Nonnull label) {
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor blackColor];
        }];
    }
    if (self.viewModel) {
        if (self.viewModel.inputType == 1) { // vin码
            self.tipLabel.text = @"请输入车辆底盘号（车身VIN号码的后八位）";
        } else {
            self.tipLabel.text = @"请输入车辆车牌号";
        }
    }
}


- (void)updateWithViewData:(id)data {
    self.viewModel = data;
    
    [self endEditing:YES];
    
    [self initWithTipLabel];
        
    for (int i=0; i<self.textFields.count; i++) {
        RZCarPlateNoTextField *view = self.textFields[i];
        if (self.viewModel.inputType == 1) { // vin码
            [view rz_changeKeyBoard:NO];
        } else {
            if (i == 0) {
                [view rz_changeKeyBoard:YES];
            } else {
                [view rz_changeKeyBoard:NO];
            }
        }
        [self.plateInputs replaceObjectAtIndex:i withObject:@""];
        view.text = @"";
    }
}

- (void)initWithTextFields {
    __weak typeof(self)weakSelf = self;
    CGFloat itemWidth = 38;
    CGFloat itemHeight = 48;
    CGFloat leftSpace = 18;
    CGFloat midSpace = (self.width - leftSpace * 2 - itemWidth * self.plateLength) / (self.plateLength - 1);
    CGRect frame = CGRectMake(leftSpace, 0, itemWidth, itemHeight);
    RZCarPlateNoTextField *preView = nil;
    for (int i=0; i<self.plateLength; i++) {
        [self.plateInputs addObject:@""];
        
        if (i != 0) {
            frame.origin.x = preView.right + midSpace;
        }
        RZCarPlateNoTextField *view = [[RZCarPlateNoTextField alloc] initWithFrame:frame];
        view.layer.borderWidth = 1;
        view.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1].CGColor;
        view.layer.cornerRadius = 3;
        view.layer.masksToBounds = YES;
        // 是否显示车牌号键盘 默认YES
        view.rz_showCarPlateNoKeyBoard = YES;
        // 是否需要校验车牌号值类型（第一位为省份或特殊号牌，中间为数字或字母，最后可能为汉字）默认YES
        view.rz_checkCarPlateNoValue = NO;
        view.textAlignment = NSTextAlignmentCenter;
        // // 最后一个输入一位，其他输入2位，第二位的时候跳格到下一个
        view.rz_maxLength = (i == self.plateLength - 1 ? 1 : 2);
        [self.textFieldContentView addSubview:view];
        view.tag = i;
        if (i != 0) {
            [view rz_changeKeyBoard:NO];
        }
        [self.textFields addObject:view];
        preView = view;
        
        view.rz_textFieldEditingValueChanged = ^(RZCarPlateNoTextField * _Nonnull textField) {
            [weakSelf textFieldValueChanged:textField];
        };
        
    }
}

- (void)initTextFields {
    NSInteger len = [self.plateNo length];
    for (int i=0; i<len; i++) {
        NSString *s= [self.plateNo substringWithRange:NSMakeRange(i, 1)];
        if (i >= self.plateLength) {
            return ;
        }
        [self.plateInputs replaceObjectAtIndex:i withObject:s];
        self.textFields[i].text = s;
    }
}

- (NSString *)getPlateNo {
    
    NSString *plate = [self.plateInputs componentsJoinedByString:@""];
    plate = [plate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    return plate;
}


- (void)textFieldValueChanged:(RZCarPlateNoTextField *)textFiled {
    NSString *originText = self.plateInputs[textFiled.tag];
    NSString *newText = textFiled.text;
    
    debugLog(@"originText=%@; newText=%@", originText, newText);
    
    RZCarPlateNoTextField *leftTextField = [self safeArrayAtIndex:textFiled.tag - 1];
    RZCarPlateNoTextField *rightTextField = [self safeArrayAtIndex:textFiled.tag + 1];
    
    RZCarPlateNoTextField *flagTextField;
    
    // 0 ..1
    if (originText.length == 0 && newText.length == 1) {
        [self.plateInputs replaceObjectAtIndex:textFiled.tag withObject:newText];
        flagTextField = rightTextField;
    } else if (originText.length == 1 && newText.length == 2) { // 1..2
        NSString *left = [newText substringToIndex:1];
        NSString *right = [newText substringFromIndex:1];
        textFiled.text = left;
        rightTextField.text = right;
        [self.plateInputs replaceObjectAtIndex:textFiled.tag withObject:left];
        if (rightTextField) {
            [self.plateInputs replaceObjectAtIndex:rightTextField.tag withObject:right];
            flagTextField = rightTextField;
        }
    } else if (originText.length == 1 && newText.length == 0){ // 1.。0
        [self.plateInputs replaceObjectAtIndex:textFiled.tag withObject:@""];
    } else if (originText.length == 0 && newText.length == 0){ // 0.。0
        [self.plateInputs replaceObjectAtIndex:textFiled.tag withObject:@""];
        flagTextField = leftTextField;
    }
    if([self regexPlateNo]) {
        flagTextField = textFiled;
    }
    if (flagTextField) {
        [flagTextField becomeFirstResponder];
    }
}

- (BOOL)regexPlateNo {
    NSString *province = self.plateInputs[0];
    NSString *provinceCode = self.plateInputs[1];
    
    NSString *last;
    NSInteger index = 2;
    for (NSInteger i = self.plateInputs.count - 1; i > 1; i--) {
        last = self.plateInputs[i];
        if (last.length > 0) {
            index = i;
            break;
        }
    }
    BOOL flag = NO;
    if (self.viewModel.inputType == 2 && ![RZCarPlateNoKeyBoardViewModel rz_regexText:province regex:rz_province_Regex]) {
        [self.plateInputs replaceObjectAtIndex:0 withObject:@""];
        flag = YES;
    }
    if (self.viewModel.inputType == 2 && ![RZCarPlateNoKeyBoardViewModel rz_regexText:provinceCode regex:rz_province_code_Regex]) {
        [self.plateInputs replaceObjectAtIndex:1 withObject:@""];
        flag = YES;
    }
    for (NSInteger i = 2; i < index; i++) {
        NSString *charText = self.plateInputs[i];
        if (self.viewModel.inputType == 2 && ![RZCarPlateNoKeyBoardViewModel rz_regexText:charText regex:rz_plateNo_code_Regex]) {
            [self.plateInputs replaceObjectAtIndex:i withObject:@""];
            flag = YES;
        }
    }
    if (self.viewModel.inputType == 2 && ![RZCarPlateNoKeyBoardViewModel rz_regexText:last regex:rz_plateNo_code_end_Regx]) {
        [self.plateInputs replaceObjectAtIndex:index withObject:@""];
        flag = YES;
    }
    if (flag) {
        __weak typeof(self) weakSelf = self;
        [self.plateInputs enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            weakSelf.textFields[idx].text = obj;
        }];
    }
    
    return flag;
}


- (RZCarPlateNoTextField *)safeArrayAtIndex:(NSInteger)index {
    if (index <= self.textFields.count - 1) {
        return self.textFields[index];
    }
    return nil;
}

@end
